﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Diagnostics;

namespace RSSReader
{
  public partial class FeedPage : PhoneApplicationPage
  {
    public class Item
    {
      public string Title { get; set; }
      public string Date { get; set; }
      public Object Color { get; set; }
      public string Body { get; set; }
      public string Url { get; set; }

      public Item(string title, string date, Object color, string body, string url)
      {
        Title = title;
        Date = date;
        Color = color;
        Body = body;
        Url = url;
      }
    }

    private Item mSelectedItem;

    public FeedPage()
    {
      InitializeComponent();
      mSelectedItem = null;
    }

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
      base.OnNavigatedTo(e);
      ParameterizedUri p = new ParameterizedUri(e.Uri);
      if (p.hasParameter("title"))
      {
        FeedItemsList.Items.Clear();
        Pivot.SelectedIndex = 0;
        feedPivot.Header = p["title"];
        if (!App.SaveData.SavedFeedItems.ContainsKey(p["title"]))
        {
          NavigationService.GoBack();
        }
        else
        {
          int i = 0;
          foreach (SaveData.FeedItem feed in App.SaveData.SavedFeedItems[p["title"]])
          {
            SolidColorBrush brush = new SolidColorBrush();
            brush.Color = Color.FromArgb(255, 255, 255, 255);
            if (i < 5)
              brush = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            ++i;
            FeedItemsList.Items.Add(new Item(feed.Title, DateTime.Now.ToLongTimeString(), brush, feed.Body, feed.URL));
          }
        }
      }
    }

    private void onFeedItemsListSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      if (e.AddedItems.Count == 1)
      {
        FeedItemsList.SelectedIndex = -1;
        Pivot.SelectedIndex = 1;
        mSelectedItem = e.AddedItems[0] as Item;
        string unescaped = mSelectedItem.Body;
        unescaped = unescaped.Replace("&quot;", "\"")
                             .Replace("&lt;", "<")
                             .Replace("&gt;", ">")
                             .Replace("&amp;", "&");
        FeedItemView.NavigateToString(unescaped);
      }
    }

    private void onBrowserOpenBtnClick(object sender, RoutedEventArgs e)
    {
      WebBrowserTask task = new WebBrowserTask();
      task.Uri = new Uri(mSelectedItem.Url, UriKind.Absolute);
      task.Show();
    }
  }
}